new Vue({
    el: '#permissions',
    data: function () {
        var _this = this;
        //element组件自定义校验手机号码的方法
        function checkMobile(rule, value, callback){
            if (value&&!_this.checkMobileJS(value)) {
                callback(new Error('手机号码格式不正确!'));
            } else {
                callback();
            }
        };
        return {
            showDialog: false, //查看dialog
            dimissionDialog: false,
            searchForm: { //查询条件
            	branch: [],
            	state:'',
            	nature:'',
                title: '',
                name: '',
                employeeNumber: '',
                dateOfStatistics: '',
                branchGroup: [],
                titleGroup: []
            },
            states: [{
				value: '在职'
			}, {
				value: '离职'
			}],
            branchs: [ //分公司
            ],
            branchs_user:[//当前用户所在的分公司
            ],
            CSOs: [
            ],
            branchGroups: [
            ],
            educations: [
            ],
            titleGroups: [
            ],
            natures: [ //岗位性质
                      ],
            titles: [ //岗位名称
            ],
            viewTitle: '', //查看or修改的title
            dimissionTitle: '',
            isDisabled: true, //disabled
            staffForm: {}, //查看修改的数据
            dimissionForm: {},
            backupsForm:{
            	branch: '',
            	CSO: ''
            },
            selectedForm: 0, //修改的位置
            currentpage:1,//当前页数
            pageBean:[//分页参数列表
            ],
            searchJson:[],
            staffList: [ { } ],//数据类型列表
            ruleForm: { //staffForm v-model
                name: ''
            },
            rules: { //from 验证
                name: [
                    {required: true, message: '请输入数据类型', trigger: 'blur'}
                ]
            },
            dRules: {
            	dimissionDate:[
        	               {required: true, message: '离职日期不能为空', trigger: 'change'}
               ],
            },
            showRules: { //新增内勤人力form 验证
            	employeeNumber: [
                    {required: true, message: '工号不能为空', trigger: 'blur'}
                ],
                branch: [
                    {required: true, message: '分公司不能为空', trigger: 'change'}
                ],
                CSO: [
                    {required: true, message: 'CSO不能为空', trigger: 'change'}
                ],
                name: [
                    {required: true, message: '姓名不能为空', trigger: 'blur'},
                    {min:2,max:20,message:'长度在 2 - 10 个字符',trigger:'blur'}
                ],
                email:[
                    {type:'email',message:'邮箱格式不正确', trigger: 'blur'}
                ],
                mobile:[
                    { validator: checkMobile, trigger: 'blur' }
                ],
                branchGroup:[
                    {required: true, message: '银保群组-机构不能为空', trigger: 'change'}
                ],
                titleGroup:[
                    {required: true, message: '银保群组-岗位不能为空', trigger: 'change'}
                ],
                isOfficeWork:[
                    {required: true, message: '内勤不能为空', trigger: 'change'}
                ],
                joinDate:[
                    {required: true, message: '入司时间不能为空', trigger: 'change'}
                ],
            },
            cso:{}
        };
    },
    created: function () {
        //页面加载查询人力列表
        this.findAllStaff();
        //页面加载查询数据字典数据
        this.getGlobalConstraints();
    },
    methods: {
    	/**
    	 * 下一页上一页按钮
    	 * */
    	handleCurrentChange:function(val){
    		this.currentpage=val;
    		var _this = this;
			this.searchStaff();
    	},
        /**
         * 查询全部的人力列表数据
         */
        findAllStaff:function() {
            var _this = this
            $.ajax({
                url: '/findAllStaff',
                type: 'post',
                data:{"page":_this.currentpage},
                dataType: 'json',
                success: function (res) {
                    _this.staffList = res.data.beanList
                    _this.groups = res.data.beanList
                    var page = {}
                    page['totalNumber'] = res.data.totalNumber
                    page['pageSize'] = res.data.size
                    _this.pageBean = page
                },
                error: function (err) {
                    if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '查询人力列表出错！错误代码：'+(err.status))
                }
            })
        },
        /**
         * 获取数据字典数据
         */
        getGlobalConstraints:function(){
            var _this = this;
            $.ajax({
                url: '/getGlobalConstraints',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    _this.cso = res
                    _this.branchs = _this.cso.data.orgnsTree.orgnsChild
                    _this.branchs.push(_this.cso.data.orgnsTree)
                    _this.natures = res.data.nature
                    _this.titles = res.data.post
                    _this.branchs_user.push(res.data.currentOrgns)
                    var cso = res;
                    _this.branchGroups = res.data.groupOrgns
                    _this.titleGroups = res.data.groupPost
                    _this.educations = res.data.ducation
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '查询人数据字典出错！错误代码：'+(err.status))
                }
            })
        },
        /**
         * 改变分公司
         * @param value
         */
    	changeBranch: function (value) {
            console.info("staffForm.CSO:",this.staffForm.CSO)
            if(this.staffForm.CSO){
                this.staffForm.CSO = "";
            }
            var $currentBranch = this.cso.data.orgnsTree.orgnsChild.filter(function (val) {
                return (val.value === value);
            })

            if($currentBranch[0].orgnsChild !== null) {
                // this.CSOs = [{"label":"","orgnsChild":"","value":""}]
                this.CSOs = ($currentBranch[0].orgnsChild)

                if($currentBranch[0].orgnsChild.length == 0 ){
                    this.CSOs.push($currentBranch[0])
                }else{
                    if($currentBranch[0].value !== $currentBranch[0].orgnsChild[$currentBranch[0].orgnsChild.length-1].value){//
                        this.CSOs.push($currentBranch[0])
                    }
                }

                //如果当前选择的是2002（广东省分公司），cso部分不显示广东省分公司南区、广东省分公司北区，
                // 直接把广东省分公司南区、广东省分公司北区的下级机构放到CSO数组中显示出来
                if(value=="2002"){
                    this.CSOs = this.getGuangDongShengNorthSouthChildOrgns(this.CSOs);
                }

                //根据json对象中的value的值去除数组中重复的数据
                this.CSOs = this.uniqueArray(this.CSOs,"value")
                this.branchs = this.uniqueArray(this.branchs,"value")

                this.CSOs.push({})

            } else {
                this.CSOs = []
                Vue.set(this.CSOs,0,$currentBranch[0])
            }
            //this.staffForm.CSO = null;
        },
        /**
         * 修改时初始化分公司
         * @param value
         */
        initializationCSO: function (value) {
        	var $currentBranch = this.cso.data.orgnsTree.orgnsChild.filter(function (val) {
        		return (val.value === value);
        	})
        	
        	if($currentBranch[0].orgnsChild !== null) {
        		// this.CSOs = [{"label":"","orgnsChild":"","value":""}]
        		this.CSOs = ($currentBranch[0].orgnsChild)
        		
        		if($currentBranch[0].orgnsChild.length == 0 ){
        			this.CSOs.push($currentBranch[0])
        		}else{
        			if($currentBranch[0].value !== $currentBranch[0].orgnsChild[$currentBranch[0].orgnsChild.length-1].value){//
        				this.CSOs.push($currentBranch[0])
        			}
        		}
        		
        		//如果当前选择的是2002（广东省分公司），cso部分不显示广东省分公司南区、广东省分公司北区，
        		// 直接把广东省分公司南区、广东省分公司北区的下级机构放到CSO数组中显示出来
        		if(value=="2002"){
        			this.CSOs = this.getGuangDongShengNorthSouthChildOrgns(this.CSOs);
        		}
        		
        		//根据json对象中的value的值去除数组中重复的数据
        		this.CSOs = this.uniqueArray(this.CSOs,"value")
        		this.branchs = this.uniqueArray(this.branchs,"value")
        		
        		this.CSOs.push({})
        		
        	} else {
        		this.CSOs = []
        		Vue.set(this.CSOs,0,$currentBranch[0])
        	}
        	//this.staffForm.CSO = null;
        },
        /**
         * 把广东省分公司南区、广东省分公司北区的下级机构放到CSO数组中
         */
        getGuangDongShengNorthSouthChildOrgns:function(csoArr){

            var csoArrNew = [];
            csoArr.forEach(function (item) {
                //广东省分公司南区、广东省分公司北区的不在cso中显示，只显示他俩的下级机构
                if(item.value== "B103050" || item.value== "B103051"){
                    csoArrNew = csoArrNew.concat(item.orgnsChild);
                }else{
                    csoArrNew.push(item)
                }
            })
            return csoArrNew;
        },
        /**
         * JSON数组去重
         * @param: [array] json Array
         * @param: [string] 唯一的key名，根据此键名进行去重
         */
        uniqueArray:function(array, key){

            var result = [array[0]];
            for(var i = 1; i < array.length; i++){
                var item = array[i];
                var repeat = false;
                for (var j = 0; j < result.length; j++) {
                    if (item[key] == result[j][key]) {
                        repeat = true;
                        break;
                    }
                }
                if (!repeat) {
                    result.push(item);
                }
            }
            return result;
        },
        /**
         * 点击新建内勤人力按钮
         */
        addStaff: function () {
        	var _this = this
            console.info("点击了新建内勤人力按钮！！！！！")
        	_this.staffForm={ "titleGroup": [],"workingDate":"","joinDate":"" }
        	_this.showDialog = true
            _this.isDisabled = false
            _this.isAdd = true
            _this.viewTitle = '新增内勤人力'
        },
        /**
         * 点击了新建内勤人力的保存按钮
         * @param formName
         */
        saveAddForm: function (formName) { // 新建内勤人力保存
            console.info("点击了新建内勤人力弹窗的保存按钮")
            var _this = this
            this.$refs[formName].validate(function (valid) {
                if (valid) {
                    $.ajax({
                        url: '/addStaff',
                        type: 'post',
                        data: {"data":JSON.stringify(_this.staffForm)},
                        dataType: 'json',
                        success: function (res) {
                            if(res.code==1){
                                successMessage(_this.$message, '创建成功！');
                                _this.showDialog = false
                                //加载人力列表
                                _this.searchStaff();
                                //把form中的数据放到staffList中
                                // this.formToStaff();
                                // Vue.set(_this.staffList, _this.selectedForm, _this.staffForm)
                            }else{
                                warningMessage(_this.$message, '创建失败！');
                            }

                        },
                        error: function (err) {
                        	if(err.responseJSON.message=="session clean"){
                                errorMessage(_this.$message, '登陆已失效重新登陆!');
                                toLogin();
                                return;
                            }
                            if(err.responseJSON.message=="employeeNumber is already exits"){
                            	errorMessage(_this.$message, '创建失败,该工号已存在!');
                            	return;
                            }
                            if(err.status == 403){
                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                return;
                            }
                            errorMessage(_this.$message,err.responseJSON.message );
                            return false
                        }
                    })
                    _this.showDialog = false
                    // Vue.set(_this.staffList, _this.selectedForm, _this.staffForm)
                }
            })
        },

        /**
         * 点击人力列表查看按钮
         * @param index
         */
        viewItem: function (index) {
            this.showDialog = true
            this.isDisabled =  true
            this.staffForm = this.staffList[index]
            this.backupsForm.branch = this.staffForm.branch;
            this.backupsForm.CSO = this.staffForm.CSO;
            this.viewTitle = '查看内勤人力'
            if(this.staffForm.workingDate!="" && this.staffForm.workingDate!=null){
            	this.calculationWorkingYears();
            }
            if(this.staffForm.joinDate!="" && this.staffForm.joinDate!=null){
            	this.calculationComYears();
            }
        },
        /**
         * 点击人力列表修改按钮
         * @param index
         */
        changeItem: function (index) {
        	var _this = this;
            this.showDialog = true
            setTimeout(function(){
            	_this.isDisabled = false
            }, 28 );
            this.staffForm = this.staffList[index]
            this.backupsForm.branch = this.staffForm.branch;
            this.backupsForm.CSO = this.staffForm.CSO;
            var branchname= this.staffForm.branch;
            var code = this.branchNameToCode(branchname);
            this.initializationCSO(code);
            this.viewTitle = '修改内勤人力'
            this.isAdd = false
            if(this.staffForm.workingDate!="" && this.staffForm.workingDate!=null){
            	this.calculationWorkingYears();
            }
            if(this.staffForm.joinDate!="" && this.staffForm.joinDate!=null){
            	this.calculationComYears();
            }
        },
        /**
         * 点击人力列表离职按钮
         * @param index
         */
        dimissionItem: function (index) {
            this.dimissionDialog = true
            var id = JSON.parse(JSON.stringify(this.staffList[index])).id;
            this.dimissionForm.name = id
            this.viewTitle = '离职内勤人力'
        },
        deleteStaff: function (formName) {
        	var _this = this
        	var id = _this.dimissionForm.name
        	var ddate = _this.dimissionForm.dimissionDate
        	this.deleteItem(id,ddate)
        	this.dimissionDialog = false
        	_this.dimissionForm.dimissionDate=''
        },
        /**
         * 删除内勤人力
         * @param index
         */
        deleteItem: function (id,ddate) {
        	var _this = this
            this.$confirm('确认要进行离职操作?离职后不可恢复', '离职提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    $.ajax({
                        url: '/deleteStaffById/'+id+'/'+ddate,
                        type: 'post',
                        dataType: 'json',
                        success: function (res) {
                            successMessage(_this.$message, '离职成功！')
                            if ( _this.pageBean['totalNumber'] % _this.pageBean.pageSize == 1 && _this.currentpage > 1) {
                                _this.currentpage -= 1;
                            }
                            _this.searchStaff()
                        },
                        error: function (err) {
                            if(err.responseJSON.message=="session clean"){
                                errorMessage(_this.$message, '登陆已失效重新登陆!');
                                toLogin();
                                return;
                            }else if(err.status == 403){
                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                return;
                            }
                            errorMessage(_this.$message, '离职出错！')
                        }
                    })
                }).catch(function () {
                        this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

        },
        searchStaffClick: function(){
        	this.currentpage = 1;
        	this.searchStaff();
        },
        /**
         * 改变查询内勤人力条件
         */
        changeSearch: function () {
        	var _this = this;
        	_this.searchJson = JSON.stringify(this.searchForm);
        	_this.currentpage = 1;
        	_this.searchStaff();
        },
        /**
         * 查询内勤人力
         */
        searchStaff: function () {
        	var _this = this;
        	if (_this.searchJson.length==0) {
        		_this.findAllStaff()
        		return
			}
        	$.ajax({
	            url: '/searchStaff',
	            type: 'post',
	            data: {"data":_this.searchJson,"page":_this.currentpage},
	            dataType: 'json',
	            success: function (res) {
	            	_this.staffList = res.data.beanList
	            	var page = {}
                    page['totalNumber'] = res.data.totalNumber
                    page['pageSize'] = res.data.size
                    _this.pageBean = page
	            },
                error: function (err) {
                    if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }else if(err.status == 403){
                        errorMessage(_this.$message, "没有权限，请先申请该权限！");
                        return;
                    }
                    errorMessage(_this.$message, '查询内勤人力失败!');
                }
	        })
        },
        /**
         * 下载查询数据
         */
        downloadFile: function(){
        	var _this = this;
        	window.location.href='/downloadFile?data='+encodeURIComponent(_this.searchJson);
        },
        /**
         * 统计内勤人力
         */
        statistics: function(){
        	var _this = this;
        	var statisticsJson = JSON.stringify(_this.searchForm);
        	window.location.href='/statistics?data='+encodeURIComponent(statisticsJson);
        },
        /**
         * 修改内勤人力的保存
         * @param formName
         */
        updateForm: function (formName) { //保存
            console.info("点击了修改内勤人力弹窗的保存按钮！！！！")
            var _this = this;
            console.info(_this.staffForm.extension);
            this.$refs[formName].validate(function (valid) {
            	if (valid) {
                    _this.branchCsoNameToCode();
                	$.ajax({
        	            url: '/updateStaffById',
        	            type: 'post',
        	            data: {"data":JSON.stringify(_this.staffForm)},
        	            dataType: 'json',
        	            success: function (res) {
                            successMessage(_this.$message, '修改成功');
                            //加载人力列表
                            _this.searchStaff();
        	            	// Vue.set(_this.staffList, _this.selectedForm, _this.staffForm)
        	            },
        	            error: function (err) {
                            if(err.responseJSON.message=="session clean"){
                                errorMessage(_this.$message, '登陆已失效重新登陆!');
                                toLogin();
                                return;
                            }
                            _this.searchStaff();
                            if(err.responseJSON.message=="employeeNumber is already exits"){
                            	errorMessage(_this.$message, '修改失败,该工号已存在!');
                            	return;
                            }
                            if (err.status == 403) {
                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                return;
                            }
        	            	errorMessage(_this.$message, '保存失败,请联系管理员!');
        	            }
        	        })

                    _this.showDialog = false
                }
            })
        },

        /**
         * 分公司或者支公司的名转成code
         */
        branchNameToCode:function(name){
            //先判断form中的branch、CSO是code还是名
        	var code = "";
            this.branchs.forEach(function (item) {
                if(item.label==name){
                	code = item.value;
                	return;
                }
            })
            return code;
        },
        
        /**
         * 把form中的分公司或者支公司的名转成code
         * 如果form中的就是code则不需要再转
         */
        branchCsoNameToCode:function(){
            //先判断form中的branch、CSO是code还是名
            var staffForm = this.staffForm;
            this.branchs.forEach(function (item) {
                if(item.label==staffForm.branch){
                    //form中存放的是名，需要转换成code
                    staffForm.branch = item.value;
                    if(staffForm.branch==staffForm.CSO){
                        //选择的分公司跟cso相同
                        staffForm.CSO = item.value;
                        return;
                    }
                    //分公司跟cso不相同
                    item.orgnsChild.forEach(function(itemChild){
                        if(itemChild.label==staffForm.CSO){
                            //form中cso存放的是名
                            staffForm.CSO = itemChild.value;
                            return;
                        }
                    })
                }
            })
        },

        /**
         * 点击弹窗中右上角关闭按钮清除校验结果
         * @param formName
         */
        closeDialog: function (formName) {
        	this.staffForm.branch = this.backupsForm.branch
        	this.staffForm.CSO = this.backupsForm.CSO
            this.$refs[formName].clearValidate()
            this.dimissionForm.dimissionDate=''
        },
        /**
         * 点击清空搜索条件按钮
         * @param formName
         */
        resetSearchForm: function (formName) {
            this.$refs[formName].resetFields()
            this.currentpage = 1
            this.findAllStaff();
        },
        getTitles: function(val,cb){
        	var _this = this;
        	var filterTitles = _this.titles.filter(function(item){
    			return item.value.indexOf(val) != -1
        	})
        	cb(filterTitles);
        },
        /**
         * js检验邮箱
         * @param mobile
         * @returns {boolean}
         */
        checkMobileJS: function (mobile){
            var reg = /^1\d{10}$/;
            return reg.test(mobile);
        },
        handleSelect: function(item) {
          console.log(item);
        },
        //同步计算工龄
        calculationWorkingYears: function(){
        	if(this.staffForm.workingDate!="" && this.staffForm.workingDate!=null){
	        	var workingDate = new Date(this.staffForm.workingDate).valueOf();
	        	var currentDate = new Date().valueOf();
	        	var difference = currentDate-workingDate;
	        	difference = new Date(difference);
	        	var result = difference.getFullYear() - 1970 + '年' + (difference.getMonth()) + '个月';
	        	this.$set(this.staffForm,'workingYears',result)
        	}
        },
        //同步计算入司时间
        calculationComYears: function(){
        	if(this.staffForm.joinDate!="" && this.staffForm.joinDate!=null){
	        	var joinDateDate = new Date(this.staffForm.joinDate).valueOf();
	        	var currentDate = new Date().valueOf();
	        	var difference = currentDate-joinDateDate;
	        	difference = new Date(difference);
	        	var result = difference.getFullYear() - 1970 + '年' + (difference.getMonth()) + '个月';
	        	this.$set(this.staffForm,'comYears',result)
	        	if((difference.getFullYear() - 1970)>=2){
	        		this.$set(this.staffForm,'isCoreStaff','是')
	        	}else{
	        		this.$set(this.staffForm,'isCoreStaff','否')
	        	}
        	}
        }
    }
})
